package com.stormkai.list;

import java.util.Arrays;
/**
 * 自定义一个ArrayList
 * @author Admin
 *
 */
public class TestArrayList2<E> {
	
	private Object[] elementData;
	private int size;
	
	private static final int DEFAULT_CAPACITY = 10;
	
	//无参构造器，可以定义ArrayList初始化的大小为10
	public TestArrayList2() {
		elementData = new Object[DEFAULT_CAPACITY];
	}
	
	//自定义创建ArrayList时候初始化数组的大小
	public TestArrayList2(int capacity) {
		
		if(capacity < 0) {
			throw new RuntimeException("容器的数量不能为负数");
		}else if(capacity == 0) {
			elementData = new Object[DEFAULT_CAPACITY];
		}else {
			elementData = new Object[capacity];
		}
		
		
	}
	
	public int size(){
		return size;
	}
	
	public  boolean isEmpty(){
		return  size==0?true:false;
	}
	
	
	public void add(E element) {
		
		//动态扩容，扩容到1.5倍
		if(size == elementData.length) {
			Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];//10+10/2
			//System.out.println(elementData.length + (elementData.length >> 1));
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			elementData = newArray;
		}
		
		
		elementData[size++] = element;
	}
	
	
	public void  remove(E  element){
		//element，将它和所有元素挨个比较，获得第一个比较为true的，返回。
		for(int i=0;i<size;i++){
			if(element.equals(get(i))){   //容器中所有的比较操作，都是用的equals而不是==
				
				//将该元素从此处移除
				remove(i);
			}
		}
	}
	
	public  void  remove(int index){
		
		//a,b,c,d,e,f,g,h
		//a,b,c,e,f,g,h,h
		int numMoved = elementData.length-index-1;
		if(numMoved>0){
			System.arraycopy(elementData, index+1, elementData, index, numMoved);
		}
		
		elementData[--size] = null;
		
	}


	@Override
	public String toString() {
		//return "TestArrayList [elementData=" + Arrays.toString(elementData) + ", size=" + size + "]";

		StringBuilder  sb = new StringBuilder();
		
		sb.append("[");
		for(int i=0;i<size;i++){
			sb.append(elementData[i]+",");
		}
		sb.setCharAt(sb.length()-1, ']'); 
		
		return  sb.toString();
	}
	
	public E get(int index) {
		checkRange(index);
		return (E)elementData[index];
	}
	
	public void set(E element, int index) {
		checkRange(index);
		
		elementData[index] = element;
	}
	
	public void checkRange(int index) {
		//索引合法判断[0,size)
		if(index < 0 || index > size - 1) {
			throw new RuntimeException("索引不合法："+index);
		}
	}

	public static void main(String[] args) {
		
		TestArrayList2<String> tList = new TestArrayList2<String>(10);
		/*tList.add("aa");
		tList.add("bb");*/
		for (int i = 0; i < 40; i++) {
			tList.add("a"+i);
		}
		
		tList.set("abc", 5);
		
		tList.remove("a7");
		
		System.out.println(tList.toString());
		System.out.println(tList.get(6));
		System.out.println(tList.size);
		System.out.println(tList.isEmpty());

	}

}
